
#include <stdint.h>

#include "Arduino.h"   // For interrupts/noInterrupts

#include "debug.h"
#include "sdcard.h"

#include <SD.h>

//
// Macro SD card slot with SPI interface uses pins: D4 (select), D11, D12, D13 
//

#define chipSelect 4

#define LOGGER_BUFFSIZE 16

//
// Filename on SD Card
//
static File logfile;

static uint8_t buffer[LOGGER_BUFFSIZE];
//static uint8_t c;
static uint32_t bufferidx = 0;

// ===================================================================
//   SD_write
// ===================================================================
void SD_write (uint8_t c)
{
  if (logfile) {

    buffer[bufferidx++] = c;  // Store character in array and increment index

    // CR record termination or buffer full? (CR+LF is common, so don't check both)
    // See notes section regarding this implementation:
    if (c == '\r' || (bufferidx >= LOGGER_BUFFSIZE-1)) {
      buffer[bufferidx] = 0; // terminate it with null at current index
      //digitalWrite(Green, HIGH);digitalWrite(Blue, LOW);
      logfile.write((uint8_t *) buffer, (bufferidx + 1)); //write the program buffer to SD lib backend buffer
      logfile.flush();
      bufferidx = 0;     // reset buffer pointer
    }
  }

  return;
}

// ===================================================================
//   SD_setup
// ===================================================================
void SD_setup (void)
{
  //
  // see if the card is present and can be initialized:
  //
  if (!SD.begin(chipSelect)) {
    PRINTF ("Card initialization failed!\n");
#if 0
    // Flash Red LED to indicate error, wait 5 sec, reboot
    int i = millis() + 5000; // 5 seconds
    Serial.println(F("Insert card or reseat card now.  Reset pending..."));
    do {
        digitalWrite(Red, LOW); delay(250); digitalWrite(Red, HIGH); delay(250);
     } while(  i > millis() );
    Serial.println("Reset!");
    delay(250);
    resetFunc();  //call reset function to reboot Arduino code
#endif
  }

  else {
    // Open the SD card logfile by name, either Create, Open, Append
    logfile = SD.open("l.txt", O_CREAT | O_WRITE | O_APPEND);
    // Test to ensure the file pointer was correctly set
    if (!logfile) {
#if 0
      int i = millis() + 5000; // 5 seconds
      Serial.print(F("Could not open logfile \n\r"));
      do {
        digitalWrite(Red, LOW); delay(250); digitalWrite(Red, HIGH); delay(250);
      } while( i > millis() ); // stay in error loop for 5 seconds
      Serial.println(F("Card write failed!  Halted..."));
      do; while(true); // halt
#endif
    } 
    else {
      PRINTF ("Writing to: europa.txt"); 
      PRINTF ("Ready to accept serial data...");
    }
  }

  bufferidx = 0;     // reset buffer pointer

  return;
}
